'use strict';

(function ($) {
    // 获取loadScriptHost
    let __useScriptHost = localStorage.getItem('__useScriptHost') == 'true'
    WPT.loadScriptHost = __useScriptHost && localStorage.getItem('__loadScriptHost')

    if (WPT.loadScriptHost) {
       // 加载本地router
       document.write(`<script src="//${WPT.loadScriptHost}/webApp/router.js.log"></script>`.replace(/\//,'\\\/'))
    }

    // 配置项目名
    var PROJECT_NAME = '双十一';

    // 添加一个Object.assign的Polyfill
    if (typeof Object.assign != 'function') {
        Object.assign = function (target) {
            'use strict';
            if (target == null) {
                throw new TypeError('Cannot convert undefined or null to object');
            }

            target = Object(target);
            for (var index = 1; index < arguments.length; index++) {
                var source = arguments[index];
                if (source != null) {
                    for (var key in source) {
                        if (Object.prototype.hasOwnProperty.call(source, key)) {
                            target[key] = source[key];
                        }
                    }
                }
            }
            return target;
        };
    }

    // ajax相关
    var _ajax = $.ajax;
    var ajax = {
        // 原始ajax
        origin: _ajax,
        // mock ajax
        mock: function mock(arg) {
            var data = Object.assign({}, arg, {
                dataType: 'jsonp',
                url: 'http://mock.weipaitang.com/api/proxy',
                data: {
                    project_name: PROJECT_NAME,
                    url: arg.url,
                    data: arg.data,
                    type: arg.type || 'get'
                },
                type: 'get'
            });

            return _ajax(data);
        }
    };

    //  模板
    var template = `
        <div id="webApp-local-develop">
        </div>
    `
    // 样式
    var style = `
        <style>
            #webApp-local-develop {
                font-size: 14px;
            }

            #webApp-local-develop .content{
                display: none;
                position: fixed;
                padding: 20px;
                top: 50%;
                left: 50%;
                background: #fff;
                backdrop-filter: blur(10px);
                transform: translate(-50%, -50%);
                z-index: 100000;
                width: 210px;
                border: 1px solid rgb(154, 151, 162);
                border-radius: 4px;
            }

            #webApp-local-develop.show .content{
                display: block;
            }

            #webApp-local-develop.show .center{
                text-align: center;
            }

            #webApp-local-develop p:nth-child(n+2) {
                margin-top: 10px;
            }

            #webApp-local-develop button, #webApp-local-develop input {
                padding: .5em;
                display: inline-block;
                border: none;
            }

            #webApp-local-develop input {
                border: 1px solid rgb(83, 82, 74);
            }

            #webApp-local-develop button {
                background: rgba(80, 142, 68, .7);
                color: #fff;
                cursor: pointer;
            }

            #webApp-local-develop .setting {
                position: fixed;
                bottom: 50px;
                left: 20px;
                z-index: 100001;
            }

            #webApp-local-develop .mock {
                background: green;
            }

            #webApp-local-develop .mock.disable {
                background: red;
            }

            #webApp-local-develop .submit {
                width: 100%;
            }

        </style>
    `

    document.head.appendChild($(style)[0])
    document.body.appendChild($(template)[0])

    function mock(){
        let state = localStorage.getItem('__useMock') == 'true'
        $.ajax = state ? ajax.mock : ajax.origin
    }

    function toggleState(key, value){
        let state = localStorage.getItem(key) == 'true'
        state = !state
        localStorage.setItem(key, state)
        mock()
        render()
    }

    function getTemplate(){
        let __useMock = localStorage.getItem('__useMock') == 'true'
        let __useScriptHost = localStorage.getItem('__useScriptHost') == 'true'
        let __loadScriptHost = localStorage.getItem('__loadScriptHost')

        return `
            <button class="setting">设置</button>
            <div class="content">
                <p>
                    数据Mock: <button class="mock ${__useMock ? 'disable' : '' }" >${__useMock ? '关闭': '启用'}</button><br />
                </p>
                <p>Mock开启后，会从mock.weipaitang.com取模拟数据</p>
                <p>
                    host开关: <button class="host-switch ${__useScriptHost ? 'disable' : '' }" >${__useScriptHost ? '关闭': '启用'}</button><br />
                    本地host: <input type="text" class="host" value="${__loadScriptHost}" /><br />
                </p>
                <p>本地host开启后，js资源会从配置的host获取</p>
                <p class="center">
                    <button class="submit">确认</button>
                </p>
            </div>
        `
    }

    var $parent
    function render(){
        $parent = $('#webApp-local-develop').html(getTemplate())
    }

    mock()
    render()

    var move = {x: 0, y:0}
    var client = move
    var change = move

    $parent.on('click', '.setting', function(){
        $parent.addClass('show')
    })
    .on('click', '.mock', function(){
        toggleState('__useMock')
    })
    .on('click', '.host-switch', function(){
        toggleState('__useScriptHost')
    })
    .on('click', '.submit', function(){
        let host = $parent.find('input').val().trim()
        localStorage.setItem('__loadScriptHost', host)
        $parent.removeClass('show')
    })
    // 设置按钮，可移动
    .on('touchstart', '.setting', function(event){
        let touch = event.touches[0]
        client = {
            x: touch.clientX,
            y: touch.clientY
        }
    })
    .on('touchmove', '.setting', function(event){
        event.preventDefault()
        let touch = event.touches[0]
        change = {
            x: touch.clientX - client.x,
            y: touch.clientY - client.y,
        }

        this.style.cssText += `;transform: translate3d(${move.x + change.x}px, ${move.y + change.y}px, 0);`
    })
    .on('touchend', '.setting', function(event){
        move = {
            x: change.x + move.x,
            y: change.y + move.y,
        }

        change = {x: 0, y: 0}
    })

})($);
